# -*- coding: utf-8 -*-
import json
from typing import List, Dict, Any
from loguru import logger
from pathlib import Path
import pandas as pd


def parse_locust_json_report(json_path: str) -> List[Dict[str, Any]]:
    """
    解析 locust JSON 报告
    :param json_path: 文件路径
    :return: 每个接口的统计数据列表
    """
    if not Path(json_path).exists():
        logger.warning(f"Locust JSON 报告文件不存在: {json_path}")
        return []

    try:
        with open(json_path, "r", encoding="utf-8") as f:
            data = json.load(f)

        result = []
        for item in data:
            result.append({
                "name": item.get("name", ""),
                "method": item.get("method", ""),
                "num_requests": item.get("num_requests", 0),
                "num_failures": item.get("num_failures", 0),
                "total_response_time": item.get("total_response_time", 0.0),
                "min_response_time": item.get("min_response_time", 0.0),
                "max_response_time": item.get("max_response_time", 0.0),
                "avg_response_time": (
                    item["total_response_time"] / item["num_requests"]
                    if item.get("num_requests", 0) > 0 else 0
                ),
                "total_content_length": item.get("total_content_length", 0),
                "response_times": item.get("response_times", {}),
                "num_reqs_per_sec": item.get("num_reqs_per_sec", {}),
                "num_fail_per_sec": item.get("num_fail_per_sec", {}),
            })
        return result
    except Exception as e:
        logger.error(f"解析 Locust JSON 失败: {e}")
        return []


def parse_locust_stats_csv_all(file_path: str, encoding: str = "utf-8"):
    """
    解析 stats.csv 文件，统一返回一个大列表，包含接口级别数据 + Aggregated 总结行（加上标记字段）。
    """
    try:
        df = pd.read_csv(file_path, encoding=encoding)

        # 清洗列名
        df.columns = [col.strip() for col in df.columns]

        # 添加标记列，标识是否为 aggregated 汇总数据
        df["is_aggregated"] = df["Name"] == "Aggregated"

        # 转换为 dict 列表返回
        all_data = df.to_dict(orient="records")
        return all_data

    except Exception as e:
        print(f"解析 CSV 文件出错: {e}")
        return []


def parse_locust_exceptions_csv(file_path: str, encoding: str = "utf-8"):
    """
    解析 Locust 生成的 exceptions.csv 或 failures.csv 文件，返回字典列表。
    """
    try:
        df = pd.read_csv(file_path, encoding=encoding)

        # 清理列名（去掉前后空格）
        df.columns = [col.strip() for col in df.columns]

        # 转换为字典列表
        records = df.to_dict(orient="records")
        return records

    except Exception as e:
        print(f"解析异常 CSV 出错: {e}")
        return []
